<?php


namespace App\Http\Controllers\Admin\Gift;


use App\Enums\GiftOpTypeEnum;
use App\Enums\GiftCategoryIdEnum;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;

//礼物
class GiftController extends BaseController
{
    /**
     * @api {get} /gift/all 获取所有礼物
     *
     * @apiGroup 礼物
     *
     * @apiParam {string} gift_name 礼物名称
     * @apiParam {int} status 状态：-1（默认）：不限制；1：上架；2：下架
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    {
    "id": 1, 序号
    "name": "萤火之森", 礼物名称
    "picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/A6d27YjxSh.png", 图片
    "special": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/QRE63PZ6tk.svga" 特效
    }
    ]
    }
     */
    public function all(Request $request)
    {
        $param = $request->only('gift_name', 'status');
        $v = app('validator')->make($param, [
            'gift_name' => 'string|max:15',
            'status' => 'integer|in:-1,1,2',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $giftName = $param['gift_name'] ?? '';
        $status = $param['status'] ?? -1;

        $where = [];
        if ($giftName) {
            $where[] = ['name', 'like', "%$giftName%"];
        }
        if ($status != -1) {
            $where[] = ['sold', '=', $status];
        }

        $list = app('model_gift')->select('id', 'name', 'picture', 'special')
            ->where($where)
            ->where('is_delete', 0)
            ->get();
        return Response::sendData($list);
    }

    /**
     * @api {get} /gift/op-types 获取操作类型下拉框（根据操作类型分类）
     *
     * @apiGroup 礼物
     *
     * @apiParam {int} op_type_category 操作类型分类，1：套装类礼物；2：互动礼物；3：魔法礼物；4：人脉信物；必须
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    {
    "id": 20,
    "name": "CP"
    },
    {
    "id": 21,
    "name": "师徒"
    },
    {
    "id": 22,
    "name": "密友"
    },
    {
    "id": 23,
    "name": "师徒扩展卡"
    },
    {
    "id": 24,
    "name": "密友扩展卡"
    }
    ]
    }
     */
    public function opTypes(Request $request)
    {
        $param = $request->only('op_type_category');
        $v = app('validator')->make($param, [
            'op_type_category' => 'required|integer|in:1,2,3,4',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $opTypeCategory = $param['op_type_category'] ?? 4;

        switch ($opTypeCategory) {
            case 1:
                $opTypes = GiftOpTypeEnum::SUIT;
                break;
            case 2:
                $opTypes = GiftOpTypeEnum::INTERACTION;
                break;
            case 3:
                $opTypes = GiftOpTypeEnum::MAGIC;
                break;
            case 4:
                $opTypes = GiftOpTypeEnum::CONNECT;
                break;
        }
        return Response::sendData(array_values($opTypes));
    }

    /**
     * @api {post} /gift/general-gift 添加普通礼物
     *
     * @apiGroup 礼物
     *
     * @apiParam {Int} category_id 分类id，无分类传0，必须
     * @apiParam {Int} gift_type 礼物类型，必须
     * @apiParam {string} gift_name 礼物名称，必须
     * @apiParam {Int} gift_price 礼物价格，必须
     * @apiParam {string} picture 图片，必须
     * @apiParam {string} special 特效
     * @apiParam {Int} gift_cardiac 心动值，必须
     * @apiParam {Int} sort 排序号，必须
     * @apiParam {Int} sale_status 销售状态，1：上架；0：下架，必须
     * @apiParam {string} gift_desc 礼物说明
     * @apiParam {string} gift_url 礼物链接
     * @apiParam {Int} gift_size 礼物大小，1：小；2：中；3：大，必须
     * @apiParam {Int} is_show_in_wall 是否在礼物墙展示，1：是；0：否，必须
     * @apiParam {string} wall_status 礼物墙状态，is_show_in_wall=1的时候必须
     * @apiParam {string} wall_desc 礼物墙说明，is_show_in_wall=1的时候必须
     * @apiParam {string} gift_tag_ids 礼物标签id，多个用英文逗号连接
     * @apiParam {int} is_lock 是否上锁，1：是；0：否；必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function add(Request $request)
    {
        $param = $request->only('category_id', 'gift_type', 'gift_name', 'gift_price', 'picture', 'special', 'gift_cardiac', 'sort', 'sale_status', 'gift_desc', 'gift_url', 'gift_size', 'is_show_in_wall', 'wall_status', 'wall_desc', 'gift_tag_ids', 'is_lock');
        $v = app('validator')->make($param, [
            'category_id' => 'required|integer',
            'gift_type' => 'required|integer',
            'gift_name' => 'required|string|max:15',
            'gift_price' => 'required|integer|min:1|max:2100000000',
            'picture' => 'required|url|max:255',
            'special' => 'url|max:255',
            'gift_cardiac' => 'required|integer|max:2100000000',
            'sort' => 'required|integer|max:2100000000',
            'sale_status' => 'required|integer|in:0,1',
            'gift_desc' => 'string|max:20',
            'gift_url' => 'url|max:255',
            'gift_size' => 'required|integer|in:1,2,3',
            'is_show_in_wall' => 'required|integer|in:0,1',
            'wall_status' => 'required_if:is_show_in_wall,1|string|max:5',
            'wall_desc' => 'required_if:is_show_in_wall,1|string|max:20',
            'gift_tag_ids' => 'string|max:30',
            'is_lock' => 'required|integer|in:0,1',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        app('repo_gift')->addOrEdit($param);
        return Response::sendData([]);
    }

    /**
     * @api {put} /gift/general-gift 编辑普通礼物
     *
     * @apiGroup 礼物
     *
     * @apiParam {Int} id 分类id，必须
     * @apiParam {Int} category_id 分类id，无分类传0，必须
     * @apiParam {Int} gift_type 礼物类型，必须
     * @apiParam {string} gift_name 礼物名称，必须
     * @apiParam {Int} gift_price 礼物价格，必须
     * @apiParam {string} picture 图片，必须
     * @apiParam {string} special 特效
     * @apiParam {Int} gift_cardiac 心动值，必须
     * @apiParam {Int} sort 排序号，必须
     * @apiParam {Int} sale_status 销售状态，1：上架；0：下架，必须
     * @apiParam {string} gift_desc 礼物说明
     * @apiParam {string} gift_url 礼物链接
     * @apiParam {Int} gift_size 礼物大小，1：小；2：中；3：大，必须
     * @apiParam {Int} is_show_in_wall 是否在礼物墙展示，1：是；0：否，必须
     * @apiParam {string} wall_status 礼物墙状态，is_show_in_wall=1的时候必须
     * @apiParam {string} wall_desc 礼物墙说明，is_show_in_wall=1的时候必须
     * @apiParam {string} gift_tag_ids 礼物标签id，多个用英文逗号连接
     * @apiParam {int} is_lock 是否上锁，1：是；0：否；必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function edit(Request $request)
    {
        $param = $request->only('id', 'category_id', 'gift_type', 'gift_name', 'gift_price', 'picture', 'special', 'gift_cardiac', 'sort', 'sale_status', 'gift_desc', 'gift_url', 'gift_size', 'is_show_in_wall', 'wall_status', 'wall_desc', 'gift_tag_ids', 'is_lock');
        $v = app('validator')->make($param, [
            'id' => 'required|integer|min:1',
            'category_id' => 'required|integer',
            'gift_type' => 'required|integer',
            'gift_name' => 'required|string|max:15',
            'gift_price' => 'required|integer|min:1|max:2100000000',
            'picture' => 'required|url|max:255',
            'special' => 'url|max:255',
            'gift_cardiac' => 'required|integer|max:2100000000',
            'sort' => 'required|integer|max:2100000000',
            'sale_status' => 'required|integer|in:0,1',
            'gift_desc' => 'string|max:20',
            'gift_url' => 'url|max:255',
            'gift_size' => 'required|integer|in:1,2,3',
            'is_show_in_wall' => 'required|integer|in:0,1',
            'wall_status' => 'required_if:is_show_in_wall,1|string|max:5',
            'wall_desc' => 'required_if:is_show_in_wall,1|string|max:20',
            'gift_tag_ids' => 'string|max:30',
            'is_lock' => 'required|integer|in:0,1',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        app('repo_gift')->addOrEdit($param);
        return Response::sendData([]);
    }

    /**
     * @api {get} /gift/general-gift 普通礼物列表
     *
     * @apiGroup 礼物
     *
     * @apiParam {string} gift_name 礼物名称
     * @apiParam {Int} sale_status 销售状态，-1（默认）：不限制；1：上架；0：下架
     * @apiParam {Int} page 第几页，默认1
     * @apiParam {Int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 580, 序号
    "category_id": 4,
    "name": "大同世界", 礼物名称
    "price": 9999, 礼物价格
    "picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/8zbs3KHDB8.png", 图片
    "special": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/dHJJSQcwHa.svga", 特效
    "sort": 2, 排序号
    "sold": 1,
    "cardiac": 50000, 礼物心动值
    "desc": "老有所终，壮有所用，幼有所长", 礼物说明
    "url": "https://www.baidu.com/?tn=40020637_10_oem_dg", 礼物链接
    "size": 3, 礼物大小，1：小；2：中；3：大
    "is_show_in_wall": 1, 是否在礼物墙展示，1：是；0：否
    "wall_status": "热销中", 礼物墙状态
    "get_method_desc": "", 礼物墙说明
    "category_name": "热销", 分类名称
    "is_lock": 1, 是否上锁，1：是；0：否
    "tags": [ 标签：
    {
    "id": 1,
    "name": "热销", 标签名称
    "bg_color": "#000000" 标签背景颜色
    },
    {
    "id": 2,
    "name": "经典",
    "bg_color": "#FFFFFF"
    }
    ],
    "suits": "春节套", 关联的套装
    "sale_status_name": "上架" 销售状态
    }
    ],
    "first_page_url": "http://local.qipaoadmin/gift?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/gift?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/gift",
    "per_page": 10,
    "prev_page_url": null,
    "to": 1,
    "total": 1
    }
    }
     */
    public function list(Request $request)
    {
        $param = $request->only('gift_name', 'sale_status', 'page', 'page_size');
        $v = app('validator')->make($param, [
            'gift_name' => 'string|max:15',
            'sale_status' => 'integer|in:-1,0,1',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $giftName = $param['gift_name'] ?? '';
        $saleStatus = $param['sale_status'] ?? -1;
        $pageSize = $param['page_size'] ?? 10;

        $where = [];
//        $where[] = ['op_type', '=', 0];
        if ($giftName) {
            $where[] = ['name', 'like', "%$giftName%"];
        }
        if ($saleStatus === '1') {
            $where[] = ['sold', '=', 1];
        } else if ($saleStatus === '0') {
            $where[] = ['sold', '=', 2];
        }

        $list = app('model_gift')
            ->select('id', 'category_id', 'name', 'price', 'picture', 'special', 'sort', 'sold', 'cardiac', 'desc', 'url', 'size', 'is_show_in_wall', 'wall_status', 'get_method_desc', 'is_lock')
            ->where($where)
            ->whereIn('op_type',[0,1])
            ->where('is_delete', 0)
            ->orderBy('id', 'desc')
            ->paginate($pageSize)->toArray();

        //批量查询分类
        $categoryIds = array_column($list['data'], 'category_id');
        $categorys = app('model_gift_categories')
            ->select('title', 'id')->whereIn('id', $categoryIds)
            ->pluck('title', 'id');
        //查询所有标签
        $tags = app('model_gift_tag')->select('id', 'name', 'bg_color')->get()->toArray();
        $tags = array_column($tags, null, 'id');
        //查询所有套装
        $suits = app('model_gift')->select('id', 'name')
            ->where('op_type', GiftOpTypeEnum::LIMITED)
            ->pluck('name', 'id')->toArray();

        foreach ($list['data'] as &$v) {
            //礼物分类
            if (isset($categorys[$v['category_id']])) {
                $v['category_name'] = $categorys[$v['category_id']];
            } else {
                $v['category_name'] = '';
            }
            //礼物标签
            $currentTagIds = app('model_gift_tag_join')->select('tag_id')->where('gift_id', $v['id'])->pluck('tag_id');
            $v['tags'] = [];
            foreach ($currentTagIds as $currentTagId) {
                if (isset($tags[$currentTagId])) {
                    $v['tags'][] = $tags[$currentTagId];
                }
            }
            //套装名称
            $suitIds = app('model_gift_suit_join')->select('suit_id')->where('gift_id', $v['id'])->pluck('suit_id');
            $v['suits'] = '';
            foreach ($suitIds as $suitId) {
                if (isset($suits[$suitId])) {
                    $v['suits'] .= $suits[$suitId] . ',';
                }
            }
            if ($v['suits']) $v['suits'] = substr($v['suits'], 0, -1);
            //状态
            if ($v['sold'] == 1) {
                $v['sale_status_name'] = '上架';
            } else if ($v['sold'] == 2) {
                $v['sale_status_name'] = '下架';
            } else {
                $v['sale_status_name'] = '';
            }
        }
        return Response::sendData($list);
    }

    /**
     * @api {post} /gift/interaction-gift 添加互动礼物
     *
     * @apiGroup 礼物
     *
     * @apiParam {Int} op_type 操作类型，普通礼物传0，必须
     * @apiParam {string} gift_name 礼物名称，必须
     * @apiParam {Int} gift_price 礼物价格，必须
     * @apiParam {string} unit 单位，必须
     * @apiParam {string} picture 图片，必须
     * @apiParam {string} special 特效
     * @apiParam {Int} gift_cardiac 心动值
     * @apiParam {Int} sale_status 销售状态，1：上架；0：下架，必须
     * @apiParam {string} gift_desc 礼物说明
     * @apiParam {string} usable_room_sys_type 可用房间系统类型，0：不限制，其它类型根据接口，多个用英文逗号连接，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function addInteraction(Request $request)
    {
        $param = $request->only('op_type', 'gift_name', 'gift_price', 'unit', 'picture', 'special', 'gift_cardiac', 'sale_status', 'gift_desc', 'usable_room_sys_type');
        $v = app('validator')->make($param, [
            'op_type' => 'required|integer|in:' . implode(',', array_keys(GiftOpTypeEnum::INTERACTION)),
            'gift_name' => 'required|string|max:15',
            'gift_price' => 'required|integer|min:1|max:2100000000',
            'unit' => 'required|string|min:1|max:4',
            'picture' => 'required|url|max:255',
            'special' => 'url|max:255',
            'gift_cardiac' => 'required|integer|max:2100000000',
            'sale_status' => 'required|integer|in:0,1',
            'gift_desc' => 'string|max:20',
            'usable_room_sys_type' => 'required|string|max:100',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $param['category_id'] = GiftCategoryIdEnum::INTERACTION;
        app('repo_gift')->addOrEdit($param);
        return Response::sendData([]);
    }

    /**
     * @api {put} /gift/interaction-gift 编辑互动礼物
     *
     * @apiGroup 礼物
     *
     * @apiParam {Int} id 礼物id，必须
     * @apiParam {Int} op_type 操作类型，普通礼物传0，必须
     * @apiParam {string} gift_name 礼物名称，必须
     * @apiParam {Int} gift_price 礼物价格，必须
     * @apiParam {string} unit 单位，必须
     * @apiParam {string} picture 图片，必须
     * @apiParam {string} special 特效
     * @apiParam {Int} gift_cardiac 心动值
     * @apiParam {Int} sale_status 销售状态，1：上架；0：下架，必须
     * @apiParam {string} gift_desc 礼物说明
     * @apiParam {string} usable_room_sys_type 可用房间系统类型，0：不限制，其它类型根据接口，多个用英文逗号连接，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function editInteraction(Request $request)
    {
        $param = $request->only('id', 'op_type', 'gift_name', 'gift_price', 'unit', 'picture', 'special', 'gift_cardiac', 'sale_status', 'gift_desc', 'usable_room_sys_type');
        $v = app('validator')->make($param, [
            'id' => 'required|integer|min:1',
            'op_type' => 'required|integer|in:' . implode(',', array_keys(GiftOpTypeEnum::INTERACTION)),
            'gift_name' => 'required|string|max:15',
            'gift_price' => 'required|integer|min:1|max:2100000000',
            'unit' => 'required|string|min:1|max:4',
            'picture' => 'required|url|max:255',
            'special' => 'url|max:255',
            'gift_cardiac' => 'required|integer|max:2100000000',
            'sale_status' => 'required|integer|in:0,1',
            'gift_desc' => 'string|max:20',
            'usable_room_sys_type' => 'required|string|max:100',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $param['category_id'] = GiftCategoryIdEnum::INTERACTION;
        app('repo_gift')->addOrEdit($param);
        return Response::sendData([]);
    }

    /**
     * @api {get} /gift/interaction-gift 互动礼物列表
     *
     * @apiGroup 礼物
     *
     * @apiParam {string} gift_name 礼物名称
     * @apiParam {Int} sale_status 销售状态，-1（默认）：不限制；1：上架；0：下架
     * @apiParam {Int} page 第几页，默认1
     * @apiParam {Int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 582, 序号
    "name": "表白", 礼物名称
    "price": 8000, 价格
    "unit": "人", 单位
    "picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/8zbs3KHDB8.png", 图片
    "special": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/dHJJSQcwHa.svga", 特效
    "cardiac": 4333, 心动值
    "sold": 1,
    "desc": "爱就勇敢表白",
    "op_type": 3,
    "room_sys_type": [
    "26",
    "30"
    ],
    "op_type_name": "表白", 互动（操作）类型
    "sale_status_name": "下架", 销售状态
    "usable_room_sys_type": "电台,男生" 可用系统房间类型
    }
    ],
    "first_page_url": "http://local.qipaoadmin/gift/interaction-gift?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/gift/interaction-gift?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/gift/interaction-gift",
    "per_page": 10,
    "prev_page_url": null,
    "to": 1,
    "total": 1
    }
    }
     */
    public function interactionList(Request $request)
    {
        $param = $request->only('gift_name', 'sale_status', 'page', 'page_size');
        $v = app('validator')->make($param, [
            'gift_name' => 'string|max:15',
            'sale_status' => 'integer|in:-1,0,1',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $giftName = $param['gift_name'] ?? '';
        $saleStatus = $param['sale_status'] ?? -1;
        $pageSize = $param['page_size'] ?? 10;

        $where = [];
        if ($giftName) {
            $where[] = ['name', 'like', "%$giftName%"];
        }
        if ($saleStatus === '1') {
            $where[] = ['sold', '=', 1];
        } else if ($saleStatus === '0') {
            $where[] = ['sold', '=', 2];
        }

        $list = app('model_gift')
            ->select('id', 'name', 'price', 'unit', 'picture', 'special', 'cardiac', 'sold', 'desc', 'op_type', 'room_sys_type')
            ->whereIn('op_type', array_keys(GiftOpTypeEnum::INTERACTION))
            ->where($where)
            ->where('is_delete', 0)
            ->orderBy('sort', 'desc')
            ->paginate($pageSize);

        //查询所有系统房间分类
        $allRoomSysType = app('model_room_type')
            ->select('room_type_name', 'id')
            ->where('type', 1)->get()->pluck('room_type_name', 'id');

        foreach ($list as &$v) {
            //互动类型
            $v->op_type_name = GiftOpTypeEnum::INTERACTION[$v->op_type]['name'];
            //状态
            $v->sale_status_name = $v->sold == 1 ? '上架' : '下架';
            //可用房间类型
            if ($v->room_sys_type) {
                $v->room_sys_type = explode(',', $v->room_sys_type);
                $v->usable_room_sys_type = '';
                foreach ($v->room_sys_type as $roomSysType) {
                    if (isset($allRoomSysType[$roomSysType])) {
                        $v->usable_room_sys_type .= $allRoomSysType[$roomSysType] . ',';
                    }
                }
                $v->usable_room_sys_type = substr($v->usable_room_sys_type, 0, -1);
            } else {
                $v->usable_room_sys_type = '全部';
            }
        }
        return Response::sendData($list);
    }

    /**
     * @api {post} /gift/magic-gift 添加魔法礼物
     *
     * @apiGroup 礼物
     *
     * @apiParam {Int} op_type 操作类型，必须
     * @apiParam {string} gift_name 礼物名称，必须
     * @apiParam {Int} gift_price 礼物价格，必须
     * @apiParam {string} picture 图片，必须
     * @apiParam {string} special 特效
     * @apiParam {Int} gift_cardiac 心动值
     * @apiParam {Int} sort 排序号，必须
     * @apiParam {Int} sale_status 销售状态，1：上架；0：下架，必须
     * @apiParam {string} gift_desc 礼物说明
     * @apiParam {string} gift_url 礼物链接
     * @apiParam {Int} is_show_in_wall 是否在礼物墙展示，1：是；0：否，必须
     * @apiParam {string} wall_status 礼物墙状态，is_show_in_wall=1的时候必须
     * @apiParam {string} wall_desc 礼物墙说明，is_show_in_wall=1的时候必须
     * @apiParam {string} gift_tag_ids 礼物标签id，多个用英文逗号连接
     * @apiParam {string} special_list 额外特效url，1-5个，多个用英文逗号连接（装扮礼物必须）
     * @apiParam {int} magic_time 魔法持续时间，单位：秒（装扮礼物、闭麦礼物必须）
     * @apiParam {int} success_probability 闭麦成功率，0~100，单位：%（闭麦礼物必须）
     * @apiParam {int} is_shock 是否振动，1：是；0：否（乌贼和碎屏必须）
     * @apiParam {int} delay_shock 振动延时的秒数（乌贼和碎屏必须）
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function addMagic(Request $request)
    {
        $param = $request->only('op_type', 'gift_name', 'gift_price', 'picture', 'special', 'gift_cardiac', 'sort', 'sale_status', 'gift_desc', 'gift_url', 'is_show_in_wall', 'wall_status', 'wall_desc', 'gift_tag_ids', 'special_list', 'magic_time', 'success_probability', 'is_shock', 'delay_shock');
        $v = app('validator')->make($param, [
            'op_type' => 'required|integer|in:' . implode(',', array_keys(GiftOpTypeEnum::MAGIC)),
            'gift_name' => 'required|string|max:15',
            'gift_price' => 'required|integer|min:1|max:2100000000',
            'picture' => 'required|url|max:255',
            'special' => 'url|max:255',
            'gift_cardiac' => 'required|integer|max:2100000000',
            'sort' => 'required|integer|min:0|max:2100000000',
            'sale_status' => 'required|integer|in:0,1',
            'gift_desc' => 'string|max:20',
            'gift_url' => 'url|max:255',
            'is_show_in_wall' => 'required|integer|in:0,1',
            'wall_status' => 'required_if:is_show_in_wall,1|string|max:5',
            'wall_desc' => 'required_if:is_show_in_wall,1|string|max:20',
            'gift_tag_ids' => 'string|max:30',
            //装扮礼物必须设置多个特效
            'special_list' => 'required_if:op_type,' . GiftOpTypeEnum::DRESS_UP . '|string|max:1250',
            //装扮礼物、闭麦礼物必须设置时长
            'magic_time' => 'required_if:op_type,' . GiftOpTypeEnum::DRESS_UP . ',' . GiftOpTypeEnum::OFF_MICROPHONE . '|integer|max:65535',
            //闭麦礼物必须设置闭麦成功率
            'success_probability' => 'required_if:op_type,' . GiftOpTypeEnum::OFF_MICROPHONE . '|integer|min:0|max:100',
            //乌贼和碎屏必须设置是否振动、振动延时的秒数
            'is_shock' => 'required_if:op_type,' . GiftOpTypeEnum::SQUID . ',' . GiftOpTypeEnum::BROKEN_SCREEN . '|integer|in:0,1',
            'delay_shock' => 'required_if:op_type,' . GiftOpTypeEnum::SQUID . ',' . GiftOpTypeEnum::BROKEN_SCREEN . '|integer',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $param['category_id'] = GiftCategoryIdEnum::MAGIC;
        app('repo_gift')->addOrEdit($param);
        return Response::sendData([]);
    }

    /**
     * @api {put} /gift/magic-gift 编辑魔法礼物
     *
     * @apiGroup 礼物
     *
     * @apiParam {Int} id 礼物id，必须
     * @apiParam {Int} op_type 操作类型，必须
     * @apiParam {string} gift_name 礼物名称，必须
     * @apiParam {Int} gift_price 礼物价格，必须
     * @apiParam {string} picture 图片，必须
     * @apiParam {string} special 特效
     * @apiParam {Int} gift_cardiac 心动值
     * @apiParam {Int} sort 排序号，必须
     * @apiParam {Int} sale_status 销售状态，1：上架；0：下架，必须
     * @apiParam {string} gift_desc 礼物说明
     * @apiParam {string} gift_url 礼物链接
     * @apiParam {Int} is_show_in_wall 是否在礼物墙展示，1：是；0：否，必须
     * @apiParam {string} wall_status 礼物墙状态，is_show_in_wall=1的时候必须
     * @apiParam {string} wall_desc 礼物墙说明，is_show_in_wall=1的时候必须
     * @apiParam {string} gift_tag_ids 礼物标签id，多个用英文逗号连接
     * @apiParam {string} special_list 额外特效url，1-5个，多个用英文逗号连接（装扮礼物必须）
     * @apiParam {int} magic_time 魔法持续时间，单位：秒（装扮礼物、闭麦礼物必须）
     * @apiParam {int} success_probability 闭麦成功率，0~100，单位：%（闭麦礼物必须）
     * @apiParam {int} is_shock 是否振动，1：是；0：否（乌贼和碎屏必须）
     * @apiParam {int} delay_shock 振动延时的秒数（乌贼和碎屏必须）
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function editMagic(Request $request)
    {
        $param = $request->only('id', 'op_type', 'gift_name', 'gift_price', 'picture', 'special', 'gift_cardiac', 'sort', 'sale_status', 'gift_desc', 'gift_url', 'is_show_in_wall', 'wall_status', 'wall_desc', 'gift_tag_ids', 'special_list', 'magic_time', 'success_probability', 'is_shock', 'delay_shock');
        $v = app('validator')->make($param, [
            'id' => 'required|integer|min:1',
            'op_type' => 'required|integer|in:' . implode(',', array_keys(GiftOpTypeEnum::MAGIC)),
            'gift_name' => 'required|string|max:15',
            'gift_price' => 'required|integer|min:1|max:2100000000',
            'picture' => 'required|url|max:255',
            'special' => 'url|max:255',
            'gift_cardiac' => 'required|integer|max:2100000000',
            'sort' => 'required|integer|min:0|max:2100000000',
            'sale_status' => 'required|integer|in:0,1',
            'gift_desc' => 'string|max:20',
            'gift_url' => 'url|max:255',
            'is_show_in_wall' => 'required|integer|in:0,1',
            'wall_status' => 'required_if:is_show_in_wall,1|string|max:5',
            'wall_desc' => 'required_if:is_show_in_wall,1|string|max:20',
            'gift_tag_ids' => 'string|max:30',
            //装扮礼物必须设置多个特效
            'special_list' => 'required_if:op_type,' . GiftOpTypeEnum::DRESS_UP . '|string|max:1250',
            //装扮礼物、闭麦礼物必须设置时长
            'magic_time' => 'required_if:op_type,' . GiftOpTypeEnum::DRESS_UP . ',' . GiftOpTypeEnum::OFF_MICROPHONE .  '|integer|max:65535',
            //闭麦礼物必须设置闭麦成功率
            'success_probability' => 'required_if:op_type,' . GiftOpTypeEnum::OFF_MICROPHONE . '|integer|min:0|max:100',
            //乌贼和碎屏必须设置是否振动、振动延时的秒数
            'is_shock' => 'required_if:op_type,' . GiftOpTypeEnum::SQUID . ',' . GiftOpTypeEnum::BROKEN_SCREEN . '|integer|in:0,1',
            'delay_shock' => 'required_if:op_type,' . GiftOpTypeEnum::SQUID . ',' . GiftOpTypeEnum::BROKEN_SCREEN . '|integer',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $param['category_id'] = GiftCategoryIdEnum::MAGIC;
        app('repo_gift')->addOrEdit($param);
        return Response::sendData([]);
    }

    /**
     * @api {get} /gift/magic-gift 魔法礼物列表
     *
     * @apiGroup 礼物
     *
     * @apiParam {Int} op_type 操作类型，0（默认）：不限制；其它根据接口
     * @apiParam {string} gift_name 礼物名称
     * @apiParam {Int} sale_status 销售状态，-1（默认）：不限制；1：上架；0：下架
     * @apiParam {Int} page 第几页，默认1
     * @apiParam {Int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 584, 序号
    "category_id": 6,
    "name": "形象设计", 礼物名称
    "price": 999, 礼物价格
    "picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/8zbs3KHDB8.png", 图片
    "special": "", 特效
    "sold": 1, 销售状态，1：上架；0：下架
    "cardiac": 166, 心动值
    "sort": 6, 排序号
    "desc": "把她变成猪头？光头？小丑？", 说明
    "url": "https://www.baidu.com/?tn=40020637_10_oem_dg", 礼物链接
    "op_type": 8,
    "is_show_in_wall": 1, 是否在礼物墙展示，1：是；0：否
    "special_list": [ 礼物特效列表url
        "http://a.jpg",
        "http://b.jpg"
    ],
    "magic_time": 10s, 时长
    "success_probability": "20%", 闭麦成功率，0%~100%
    "is_shock": "否", 是否振动
    "category_name": "魔法", 分类名称
    "tags": [ 礼物标签：
    {
    "id": 1,
    "name": "热销", 标签名称
    "bg_color": "#000000" 标签背景颜色
    },
    {
    "id": 2,
    "name": "经典",
    "bg_color": "#FFFFFF"
    },
    {
    "id": 3,
    "name": "限定",
    "bg_color": "#00FF00"
    }
    ],
    "join_product_info": [ 关联商品信息：
    {
    "picture": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/2091cb9072a2d0ebc5387a46a76f0926H1Vrp.png", 图片
    "special": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/589880618b94285f612764664cd22306iAxGQ.mp4" 特效
    },
    {
    "picture": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/42fd2cb11a0a78ae6a1e11970595f0d9wiDkg.png",
    "special": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/6a88c38a8f39f662453bbff85d42908bj7TzQ.mp4"
    }
    ]
    }
    ],
    "op_type_name": "佩戴装扮" 操作类型名称
    "first_page_url": "http://local.qipaoadmin/gift/magic-gift?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/gift/magic-gift?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/gift/magic-gift",
    "per_page": 10,
    "prev_page_url": null,
    "to": 1,
    "total": 1
    }
    }
     */
    public function magicList(Request $request)
    {
        $param = $request->only('op_type', 'gift_name', 'sale_status', 'page', 'page_size');
        $v = app('validator')->make($param, [
            'op_type' => 'integer|min:0',
            'gift_name' => 'string|max:15',
            'sale_status' => 'integer|in:-1,0,1',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $opType = $param['op_type'] ?? 0;
        $giftName = $param['gift_name'] ?? '';
        $saleStatus = $param['sale_status'] ?? -1;
        $pageSize = $param['page_size'] ?? 10;

        $where = [];
        if ($opType > 0) {
            $where[] = ['g.op_type', '=', $opType];
        }
        if ($giftName) {
            $where[] = ['g.name', 'like', "%$giftName%"];
        }
        if ($saleStatus === '1') {
            $where[] = ['g.sold', '=', 1];
        } else if ($saleStatus === '0') {
            $where[] = ['g.sold', '=', 2];
        }

        $list = app('model_gift')->from('ln_gift as g')
            ->leftJoin('ln_gift_extend as ge', 'g.id', '=', 'ge.gift_id')
            ->select('g.id', 'g.category_id', 'g.name', 'g.price', 'g.picture', 'g.special', 'g.sold', 'g.cardiac', 'g.sort', 'g.desc', 'g.url', 'g.op_type', 'is_show_in_wall', 'ge.magic_ext')
            ->whereIn('g.op_type', array_keys(GiftOpTypeEnum::MAGIC))
            ->where($where)
            ->where('g.is_delete', 0)
            ->orderBy('g.sort', 'desc')
            ->paginate($pageSize)->toArray();

        //批量查询分类
        $categoryIds = array_column($list['data'], 'category_id');
        $categorys = app('model_gift_categories')
            ->select('title', 'id')->whereIn('id', $categoryIds)
            ->pluck('title', 'id');
        //查询所有标签
        $tags = app('model_gift_tag')->select('id', 'name', 'bg_color')->get()->toArray();
        $tags = array_column($tags, null, 'id');

        foreach ($list['data'] as &$v) {
            //礼物分类
            if (isset($categorys[$v['category_id']])) {
                $v['category_name'] = $categorys[$v['category_id']];
            } else {
                $v['category_name'] = '';
            }
            //礼物标签
            $currentTagIds = app('model_gift_tag_join')->select('tag_id')->where('gift_id', $v['id'])->pluck('tag_id');
            $v['tags'] = [];
            foreach ($currentTagIds as $currentTagId) {
                if (isset($tags[$currentTagId])) {
                    $v['tags'][] = $tags[$currentTagId];
                }
            }
            //销售状态
            $v['sold'] = $v['sold'] == 1 ? 1 : 0;
            //扩展字段
            $extFields = json_decode($v['magic_ext'], true);
            //装扮礼物
            $v['special_list'] = [];
            $v['magic_time'] = $v['success_probability'] = $v['is_shock'] = $v['delay_shock'] = $v['delay_shock'] = '';

            if ($v['op_type'] == GiftOpTypeEnum::DRESS_UP) {
                $v['special_list'] = $extFields['special_list'];
                $v['magic_time'] = $extFields['magic_time'];
            }
            //闭麦礼物
            if ($v['op_type'] == GiftOpTypeEnum::OFF_MICROPHONE) {
                $v['success_probability'] = $extFields['success_probability'];
                $v['magic_time'] = $extFields['magic_time'];
            }
            //乌贼和碎屏
            if ($v['op_type'] == GiftOpTypeEnum::SQUID || $v['op_type'] == GiftOpTypeEnum::BROKEN_SCREEN) {
                $v['is_shock'] = $extFields['is_shock']; //是否振动
                $v['delay_shock'] = $extFields['delay_shock']; //振动延时的秒数
            }
            //操作类型名称
            $v['op_type_name'] = GiftOpTypeEnum::MAGIC[$v['op_type']]['name'];
        }
        return Response::sendData($list);
    }

    /**
     * @api {post} /gift/suit-gift 添加限定礼物
     *
     * @apiGroup 礼物
     *
     * @apiParam {string} gift_name 礼物名称，必须
     * @apiParam {string} picture 图片，必须
     * @apiParam {Int} sort 排序号，必须
     * @apiParam {Int} sale_status 销售状态，1：上架；0：下架，必须
     * @apiParam {string} gift_desc 礼物说明
     * @apiParam {string} join_gift_info 关联礼物信息，json格式，示例：[{"gift_id":348,"is_rare":1},{"gift_id":349,"is_rare":1},{"gift_id":350,"is_rare":0}]，gift_id：礼物id；is_rare：是否稀有，1：是；0：否
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function addSuit(Request $request)
    {
        $param = $request->only('gift_name', 'picture', 'sort', 'sale_status', 'gift_desc', 'join_gift_info');
        $v = app('validator')->make($param, [
            'gift_name' => 'required|string|max:15',
            'picture' => 'required|url|max:255',
            'sort' => 'required|integer|min:0|max:2100000000',
            'sale_status' => 'required|integer|in:0,1',
            'gift_desc' => 'string|max:20',
            'join_gift_info' => 'required',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $param['module'] = 3;
        $param['op_type'] = GiftOpTypeEnum::LIMITED;

        app('repo_gift')->addOrEditSuit($param);
        return Response::sendData([]);
    }

    /**
     * @api {put} /gift/suit-gift 编辑限定礼物
     *
     * @apiGroup 礼物
     *
     * @apiParam {int} id 礼物id，必须
     * @apiParam {string} gift_name 礼物名称，必须
     * @apiParam {string} picture 图片，必须
     * @apiParam {Int} sort 排序号，必须
     * @apiParam {Int} sale_status 销售状态，1：上架；0：下架，必须
     * @apiParam {string} gift_desc 礼物说明
     * @apiParam {string} join_gift_info 关联礼物信息，json格式，示例：[{"gift_id":348,"is_rare":1},{"gift_id":349,"is_rare":1},{"gift_id":350,"is_rare":0}]，gift_id：礼物id；is_rare：是否稀有，1：是；0：否
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function editSuit(Request $request)
    {
        $param = $request->only('id', 'gift_name', 'picture', 'sort', 'sale_status', 'gift_desc', 'join_gift_info');
        $v = app('validator')->make($param, [
            'id' => 'required|integer|min:1',
            'gift_name' => 'required|string|max:15',
            'picture' => 'required|url|max:255',
            'sort' => 'required|integer|min:0|max:2100000000',
            'sale_status' => 'required|integer|in:0,1',
            'gift_desc' => 'string|max:20',
            'join_gift_info' => 'required',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $param['module'] = 3;
        $param['op_type'] = GiftOpTypeEnum::LIMITED;

        app('repo_gift')->addOrEditSuit($param);
        return Response::sendData([]);
    }

    /**
     * @api {get} /gift/suit-gift 限定礼物列表
     *
     * @apiGroup 礼物
     *
     * @apiParam {string} gift_name 礼物名称
     * @apiParam {Int} sale_status 销售状态，-1（默认）：不限制；1：上架；0：下架
     * @apiParam {Int} page 第几页，默认1
     * @apiParam {Int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 589, 序号
    "name": "仲夏之梦", 名称
    "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5fda0a3c1a243.png", 图片
    "sold": 1, 销售状态，1：上架；0：下架
    "desc": "看风使舵", 说明
    "sort": 1, 排序号
    "created_at": "2021-08-17 16:47:00" 创建时间
    }
    ],
    "first_page_url": "http://local.qipaoadmin/gift/suit-gift?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/gift/suit-gift?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/gift/suit-gift",
    "per_page": 10,
    "prev_page_url": null,
    "to": 1,
    "total": 1
    }
    }
     */
    public function suitList(Request $request)
    {
        $param = $request->only('gift_name', 'sale_status', 'page', 'page_size');
        $v = app('validator')->make($param, [
            'gift_name' => 'string|max:15',
            'sale_status' => 'integer|in:-1,0,1',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $giftName = $param['gift_name'] ?? '';
        $saleStatus = $param['sale_status'] ?? -1;
        $pageSize = $param['page_size'] ?? 10;

        $where = [];
        if ($giftName) {
            $where[] = ['name', 'like', "%$giftName%"];
        }
        if ($saleStatus === '1') {
            $where[] = ['sold', '=', 1];
        } else if ($saleStatus === '0') {
            $where[] = ['sold', '=', 2];
        }

        $list = app('model_gift')
            ->select('id', 'name', 'picture', 'sold', 'desc', 'sort', 'created_at')
            ->where('op_type', GiftOpTypeEnum::LIMITED)
            ->where($where)
            ->where('is_delete', 0)
            ->orderBy('sort', 'desc')
            ->paginate($pageSize);
        foreach ($list as &$v) {
            if ($v['sold'] == 2) {
                $v['sold'] == 0;
            }
        }

        return Response::sendData($list);
    }

    /**
     * @api {get} /gift/detail 获取礼物详情
     *
     * @apiGroup 礼物
     *
     * @apiParam {Int} id 礼物id
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "id": 584, 礼物id
    "category_id": 6, 礼物分类id
    "type": 1, 礼物类型
    "name": "形象设计", 礼物名称
    "picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/8zbs3KHDB8.png", 图片
    "price": 999, 价格
    "unit": "", 单位
    "special": "", 特效
    "sort": 6, 排序号
    "type": 26,
    "sold": 1, 销售状态，1：上架；0：下架
    "cardiac": 0, 心动值
    "frame_id": 0,
    "module": 1,
    "desc": "把她变成猪头？光头？小丑？", 说明
    "url": "https://www.baidu.com/?tn=40020637_10_oem_dg", 礼物链接
    "size": 3, 大小，1：小；2：中；3：大
    "is_show_in_wall": 1, 是否在礼物墙展示，1：是；0：否
    "wall_status": "", 礼物墙状态
    "op_type": 8, 操作类型
    "room_sys_type": "0|[2,4]", 可用房间系统分类，0：不限制
    "created_at": "2021-08-17 13:12:15", 创建时间
    "updated_at": "2021-08-17 13:12:15",
    "is_lock": 0, 锁定，1：是；0：否
    "gift_id": 584,
    "special_list": [ 特效列表（仅装扮礼物有）：
    "http://a.jpg",
    "http://b.jpg"
    ],
    "magic_time": 10, 效果时长
    "success_probability": 20, 闭麦成功率，单位：%
    "is_shock": 0, 是否振动，1：是；0：否
    "relation_name": "", 关系名称
    "connect_level": 1, 人脉关系等级
    "tag_ids": [ 关联的标签id：
    1,
    2,
    3
    ],
    "suit_gifts": [ 套装包含的礼物（限定礼物有值）：
    {
    "id": 1, 礼物id
    "name": "随便花", 礼物名称
    "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5fad49cacc82b.png", 图片
    "special": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5fad49cdaf2a5.png", 特效
    "is_rare": 1 是否稀有，1：是；0：否
    }
    ]
    }
    }
     */
    public function detail(Request $request)
    {
        $id = $request->id;

        $detail = app('model_gift')->from('ln_gift as g')
            ->leftJoin('ln_gift_extend as ge', 'g.id', '=', 'ge.gift_id')
            ->where('id', $id)
            ->first();
        if ($detail->sold == 2) $detail->sold = 0;

        $detail->room_sys_type = explode(',', $detail->room_sys_type);

        if ($detail->special_list) {
            $detail->special_list = explode(',', $detail->special_list);
        } else {
            $detail->special_list = [];
        }
        //关联标签
        $detail->tag_ids = app('model_gift_tag_join')->select('tag_id')->where('gift_id', $id)->pluck('tag_id');
        //关联套装
        $detail->suit_gifts = app('model_gift_suit_join')->from('ln_gift_suit_join as gsj')
            ->leftJoin('ln_gift as g', 'gsj.gift_id', '=', 'g.id')
            ->select('g.id', 'g.name', 'g.picture', 'g.special', 'gsj.is_rare')
            ->where('gsj.suit_id', $id)
            ->get();
        return Response::sendData($detail);
    }

    /**
     * @api {put} /gift/status 修改状态
     *
     * @apiGroup 礼物
     *
     * @apiParam {Int} id 礼物id
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": 1 修改后的状态，1：上架；0：下架
    }
     */
    public function editStatus(Request $request)
    {
        $id = $request->id;

        $gift = app('model_gift')->select('sold')->where('id', $id)->first();
        if (empty($gift)) throw new BasicException(0, '礼物id错误');

        if ($gift->sold == 1) {
            $status = 2;
        } else {
            $status = 1;
        }
        $res = app('model_gift')->where('id', $id)->update(['sold' => $status]);
        if ($status == 2) $status = 0;
        if ($res) {
            return Response::sendData($status);
        } else {
            throw new BasicException(0, '操作失败');
        }
    }

    /**
     * @api {put} /gift/set-top 置顶
     *
     * @apiGroup 礼物
     *
     * @apiParam {Int} id 礼物id
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function setTop(Request $request)
    {
        $id = $request->id;

        $gift = app('model_gift')->select('id')->where('id', $id)->first();
        if (empty($gift)) throw new BasicException(0, '礼物id错误');

        $maxSort = app('model_gift')->max('sort');
        $maxSort++;

        $res = app('model_gift')->where('id', $id)->update(['sort' => $maxSort]);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '置顶失败');
        }
    }

    /**
     * @api {delete} /gift 删除礼物
     *
     * @apiGroup 礼物
     *
     * @apiParam {string} ids 礼物id，多个用英文逗号连接
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function del(Request $request)
    {
        $ids = $request->ids;

        if (empty($ids)) throw new BasicException(0, '请选择要删除的记录');

        $ids = explode(',', $ids);

        $res = app('model_gift')->whereIn('id', $ids)->update(['is_delete' => 1]);
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '删除失败');
    }

    /**
     * @api {post} /gift/give 赠送礼物
     *
     * @apiGroup 礼物
     *
     * @apiParam {int} user_code 用户编号，必须
     * @apiParam {int} gift_id 礼物id，必须
     * @apiParam {int} gift_num 礼物数量，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function give(Request $request)
    {
        $param = $request->only('user_code', 'gift_id', 'gift_num','remark');
        $v = app('validator')->make($param, [
            'user_code' => 'required|integer',
            'gift_id' => 'required|integer',
            'gift_num' => 'required|integer|min:1|max:10000',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $userCode = $param['user_code'];
        $giftId = $param['gift_id'];
        $giftNum = $param['gift_num'];
        $remark = $request->input('remark','');
        $admin_id = $request->admin_id;
        $res = app('repo_gift')->give($giftId, $giftNum, 0, $userCode,$remark,$admin_id);
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '赠送失败');
    }

    /**
     * @api {post} /gift/status-crontab 设置定时上下架任务
     *
     * @apiGroup 礼物
     *
     * @apiParam {int} id 礼物id
     * @apiParam {int} action 操作，1：上架；0：下架
     * @apiParam {string} set_time 定时时间，YYYY-mm-dd HH:ii:ss
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function addStatusCrontab(Request $request)
    {
        $param = $request->only('id', 'action', 'set_time');
        $v = app('validator')->make($param, [
            'id' => 'required|integer|min:1',
            'action' => 'required|integer|in:0,1',
            'set_time' => 'required|date_format:Y-m-d H:i:s',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $id = $param['id'];
        $action = $param['action'];
        $setTime = $param['set_time'];

        $gift = app('model_gift')->select('sold')->where('id', $id)->first();
        if (empty($gift)) throw new BasicException(0, '礼物id错误');

        if ($gift->sold == 1 && $action == 1) {
            throw new BasicException(0, '礼物已经是上架状态');
        }
        if ($gift->sold == 2 && $action == 0) {
            throw new BasicException(0, '礼物已经是下架状态');
        }
        if ($setTime <= date('Y-m-d H:i:s')) {
            throw new BasicException(0, '定时时间必须大于当前时间');
        }

        $crontab = app('model_gift_status_crontab')
            ->select('id')
            ->where('gift_id', $id)->where('action', $action)->where('status', 0)
            ->first();
        //有未处理的同类型定时任务则更新，否则新增
        if ($crontab) {
            $res = app('model_gift_status_crontab')->where('id', $crontab->id)->update(['set_time' => $setTime]);
        } else {
            $res = app('model_gift_status_crontab')->insert([
                'gift_id' => $id,
                'action' => $action,
                'set_time' => $setTime,
            ]);
        }
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '设置失败');
    }

    /**
     * @api {get} /gift/status-crontab 定时上下架任务列表
     *
     * @apiGroup 礼物
     *
     * @apiParam {string} gift_name 礼物名称
     * @apiParam {int} page 第几页，默认1
     * @apiParam {int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 1, 序号
    "gift_id": 584, 礼物id
    "action": 0, 操作，1：上架；0：下架
    "set_time": "2021-08-22 13:12:44", 定时时间
    "status": 0, 定时任务状态：0：未执行；1：已执行
    "gift_name": "形象设计", 礼物名称
    "gift_picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/8zbs3KHDB8.png", 礼物图片
    "gift_status": 1 礼物状态：1：上架；0：下架
    }
    ],
    "first_page_url": "http://local.qipaoadmin/gift/status-crontab?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/gift/status-crontab?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/gift/status-crontab",
    "per_page": 10,
    "prev_page_url": null,
    "to": 1,
    "total": 1
    }
    }
     */
    public function statusCrontabList(Request $request)
    {
        $param = $request->only('gift_name', 'page', 'page_size');
        $v = app('validator')->make($param, [
            'gift_name' => 'string|max:15',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $giftName = $param['gift_name'] ?? '';
        $pageSize = $param['page_size'] ?? 10;

        $whereFunc = [];
        if ($giftName) {
            $giftIds = app('model_gift')->where('name', 'like', "%$giftName%")->pluck('id')->toArray();
            $whereFunc = function ($query) use ($giftIds) {
                $query->whereIn('gift_id', $giftIds);
            };
        }

        $list = app('model_gift_status_crontab')
            ->select('id', 'gift_id', 'action', 'set_time', 'status')
            ->where($whereFunc)
            ->orderBy('id', 'desc')
            ->paginate($pageSize)->toArray();

        //批量查询礼物信息
        $giftIds = array_column($list['data'], 'gift_id');
        $gifts = app('model_gift')->select('id', 'name', 'picture', 'sold')->whereIn('id', $giftIds)->get()->toArray();
        $gifts = array_column($gifts, null, 'id');

        foreach ($list['data'] as &$v) {
            if (isset($gifts[$v['gift_id']])) {
                $v['gift_name'] = $gifts[$v['gift_id']]['name'];
                $v['gift_picture'] = $gifts[$v['gift_id']]['picture'];
                $v['gift_status'] = $gifts[$v['gift_id']]['sold'] == 1 ? 1 : 0;
            } else {
                $v['gift_name'] = '';
                $v['gift_picture'] = '';
                $v['gift_status'] = '';
            }
        }
        return Response::sendData($list);
    }

    /**
     * @api {delete} /gift/status-crontab 删除定时上下架任务
     *
     * @apiGroup 礼物
     *
     * @apiParam {int} id 要删除的定时任务id
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function delStatusCrontab(Request $request)
    {
        $param = $request->only('id');
        $v = app('validator')->make($param, [
            'id' => 'required|integer|min:1',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $id = $param['id'];

        $statusCrontab = app('model_gift_status_crontab')->select('status')->where('id', $id)->first();
        if (empty($statusCrontab)) throw new BasicException(0, 'id错误，任务不存在');

        if ($statusCrontab->status == 1) {
            throw new BasicException(0, '已执行的定时任务不能删除');
        }

        $res = $statusCrontab->where('id', $id)->delete();
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '删除失败');
    }
}
